package com.lottery.material.controller.portal.circle;

import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.jedis.JedisClient;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.circle.CircleMemberInfo;
import com.lottery.material.pojo.circle.CircleNoticeInfo;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.resolver.CustomException;
import com.lottery.material.service.portal.circle.CircleInfoService;
import com.lottery.material.service.portal.circle.CircleMemberInfoService;
import com.lottery.material.service.portal.circle.CircleNoticeInfoService;
import com.lottery.material.service.portal.circle.CircleRuleConfigService;
import com.lottery.material.service.portal.user.PortalUserInfoService;
import com.lottery.material.util.ExceptionUtil;
import com.lottery.material.util.ParameterUtil;
import com.lottery.material.util.ResponseResult;
import com.lottery.material.vo.portal.circle.CircleInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 肖拔赟
 * @Description 圈子
 * @DATE Created on 2019-04-08 9:36
 */
@Api(value = "圈子", tags = "圈子")
@Controller
@RequestMapping("/portal/circle")
@Slf4j
public class CircleInfoController extends BaseController {

    @Autowired
    private CircleInfoService circleInfoService;
    @Autowired
    private CircleMemberInfoService circleMemberInfoService;
    @Autowired
    private CircleNoticeInfoService circleNoticeInfoService;
    @Autowired
    private CircleRuleConfigService circleRuleConfigService;
    @Autowired
    private PortalUserInfoService portalUserInfoService;
    @Autowired
    @Qualifier("jedisClientCluster")
    private JedisClient jedisClient;

    @ApiOperation(value = "获取圈子详情", notes = "获取圈子详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "circleId", value = "圈子id", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult get(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<String, String>();
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }
        final String circleId = reqParamMap.get("circleId");
        CircleInfo circleInfo = circleInfoService.findById(Integer.valueOf(circleId));
        CircleInfoVo circleInfoVo = new CircleInfoVo(circleInfo);
        circleInfoVo.setNotices(circleNoticeInfoService.findByCircleId(circleId));//公告列表

        String userId = reqParamMap.get("userId");
        String accessToken = reqParamMap.get("accessToken");
        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(accessToken)) {
            Object hget = jedisClient.hget("portalUser", userId);
            String s = String.valueOf(hget);
            if (!accessToken.equals(s)) {
                return ResponseResult.buildResult(ResultEnum.LOGIN_OUTOFDATE_ERROR);
            }

            PageData pd = new PageData();
            pd.put("userId", userId);
            pd.put("circleId", circleId);
            CircleMemberInfo circleMemberInfo = circleMemberInfoService.findByUserIdAndCircleId(pd);
            if (null != circleMemberInfo) {//圈子--是否关注（1：否；2：是）
                circleInfoVo.setIsFollow("2");
            } else {
                circleInfoVo.setIsFollow("1");
            }
        }else {
            circleInfoVo.setIsFollow("1");
        }

        //圈子--人气榜粉丝头像top10
        circleInfoVo.setFansIcons(circleMemberInfoService.getFansTop10(circleId));
        return ResponseResult.buildSuccess(circleInfoVo);

    }

    /**
     * @Author 肖拔赟
     * @Description 搜索圈子列表接口
     * @Date Created on 2019-04-08 13:46
     * @param
     * @return
     */
    @ApiOperation(value = "搜索圈子列表接口", notes = "搜索圈子列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "搜索关键字", required = true, dataType = "String")
    })
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult search(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<String, String>();
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }

        try {
            //查询Circle封装成VO
            return ResponseResult.buildSuccess(circleInfoService.findByCircleNameLike(URLDecoder.decode(reqParamMap.get("content"),"utf-8")));
        } catch (Exception e) {
            log.error("【获取Circle出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_CIRCLE_INFO_LIST_EXCEPTION);
        }
    }


    /**
     * @Author 肖拔赟
     * @Description 获取我的关注圈子列表接口
     * @Date Created on 2019-04-08 16:37
     * @param
     * @return
     */
    @ApiOperation(value = "获取我的关注圈子列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId",required = true)
    })
    @RequestMapping(value = "/attenttion" , method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult attenttion(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<String, String>();
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }
        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);


        try {
            //查询Circle封装成VO
            List<CircleInfoVo> list = circleMemberInfoService.findAttentionByUserId(reqParamMap.get("userId"));

            return ResponseResult.buildSuccess(list);
        } catch (Exception e) {
            log.error("【获取我的关注圈子列表出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_CIRCLE_ATTENTTION_LIST_EXCEPTION);
        }

    }


    /**
     * @Author 肖拔赟
     * @Description 申请成为正式圈员
     * @Date Created on 2019-04-08 16:37
     */
    /*@ResponseBody
    @RequestMapping(value = "/applyIn", method = RequestMethod.POST)
    public ResponseResult applyIn(HttpServletRequest request) {
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }
        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient);

        final String circleId = reqParamMap.get("circleId");
        final String userId = reqParamMap.get("userId");
        try{
            //验证该圈子是否存在
            CircleInfo circleInfo = circleInfoService.findById(Integer.valueOf(circleId));
            if(circleInfo == null){
                throw new CustomException(ResultEnum.GET_CIRCLE_NOT_FOUND_EXCEPTION);
            }

            PageData pd = new PageData();
            pd.put("userId", userId);
            pd.put("circleId", circleId);
            CircleMemberInfo circleMemberInfo = circleMemberInfoService.findByUserIdAndCircleId(pd);
            if(null == circleMemberInfo){
                return ResponseResult.buildResult(400, "请先关注圈子");
            }
            log.info("申请成为正式圈员 circleId->{}, userId->{}....");
            if(1 == circleMemberInfo.getRank()){
                circleMemberInfo.setRank(2);
                circleMemberInfo.setCreateTime(new Date());
                circleMemberInfoService.save(circleMemberInfo);
            }



        } catch (Exception e) {
            log.error("【申请成为正式圈员出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_CIRCLE_APPLY_IN_EXCEPTION);
        }
        return null;


    }*/


    /**
     * @Author 肖拔赟
     * @Description 申请成为正式圈员规则
     * @Date Created on 2019-04-08 16:37
     */
    @ApiOperation(value = "申请成为正式圈员规则", notes = "申请成为正式圈员规则")
    @ResponseBody
    @RequestMapping(value = "/getRule", method = RequestMethod.POST)
    public ResponseResult getRule(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<String, String>();
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }
        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        try {
            return ResponseResult.buildSuccess(circleRuleConfigService.findCircleRule());
        }catch (Exception e){
            log.error("【获取申请成为正式圈员规则出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_CIRCLE_GET_RULE_EXCEPTION);
        }

    }


    /**
     * @Author 肖拔赟
     * @Description 5.5	获取圈子成员接口
     * @Date Created on 2019-04-22 20:22
     */
    @ApiOperation(value = "获取圈子成员接口", notes = "获取圈子成员接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "查询类型（1：全部；2：禁言用户；3：未验证用户）", value = "queryType", required = true),
            @ApiImplicitParam(name = "圈子Id", value = "circleId", required = true),
            @ApiImplicitParam(name = "分页页码", value = "page", required = true)
    })
    @RequestMapping(value = "/userList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getCircleUser(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<String, String>();
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }

        final String currentPage = reqParamMap.get("page");
        final String circleId = reqParamMap.get("circleId");
        final String queryType = reqParamMap.get("queryType");
        if (StringUtils.isBlank(currentPage)) {
            return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(),
                    String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"page"));
        }
        if(StringUtils.isBlank(circleId)){
            return ResponseResult.buildResult(400, "圈子Id不能为空");
        }


        try{
            List<Map<String, String>>  list = circleInfoService.getMemberUserListPage(circleId, queryType, Integer.valueOf(currentPage));
            return ResponseResult.buildSuccess(list);
        }catch (Exception e){
            log.error("获取圈子成员接口异常->{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_CIRCLE_MEMBER_USER_EXCEPTION);
        }


    }

    /**
     * @Author 肖拔赟
     * @Description 5.2	获取圈子列表接口
     * @Date Created on 2019-04-22 20:22
     */
    @ApiOperation(value = "获取圈子列表接口",notes = "获取圈子列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuCode", value = "菜单级别编号", required = true),
            @ApiImplicitParam(name = "userId", value = "userId", required = false)
    })
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult list(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<String, String>();
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }

        final String menuCode = reqParamMap.get("menuCode");
        if(StringUtils.isBlank(menuCode)){
            return ResponseResult.buildResult(400, "菜单级别编号不能为空");
        }

        try{
            return ResponseResult.buildSuccess(
                    circleInfoService.getCircleByMenuCode(menuCode, reqParamMap.get("userId")));
        }catch (Exception e){
            log.error("【获取圈子列表接口出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_CIRCLE_INFO_LIST_EXCEPTION);
        }

    }

}
